package com.yonyou.distribute.zk;


import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.CountDownLatch;

@Component
public class ZKClient_3 {

    private ZooKeeper zooKeeper;

    @PostConstruct
    public void init(){//获取连接，项目启动时获取
        try {
            // 计数器对象
            CountDownLatch countDownLatch=new CountDownLatch(1);
            // arg1:服务器的ip和端口
            // arg2:客户端与服务器之间的会话超时时间  以毫秒为单位的
            // arg3:监视器对象
            zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    if(event.getState() == Event.KeeperState.SyncConnected) {
                        System.out.println("连接创建成功！");
                        countDownLatch.countDown();
                    }
                }
            });
            // 主线程阻塞等待连接对象的创建成功
            countDownLatch.await();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @PreDestroy
    public void destroy(){
        try {
            if(zooKeeper != null){
                zooKeeper.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public ZKDistributedLock_3 getLock(String lockName){
        return new ZKDistributedLock_3(zooKeeper, lockName);
    }
}
